import puppeteer from "puppeteer";
import path from "path";
import fs from "fs";
// import en from "./lang/en.json" assert { type: "json" };
const en = JSON.parse(fs.readFileSync("./lang/en.json", "utf8"));
// 使用jsonData对象进行操作

const __dirname = path.dirname(new URL(import.meta.url).pathname);
// const appendFile = util.promisify(fs.appendFile);

const CONFIG = {
  input: "lang/en.json",
  list: ["jp", "zh", "de", "spa", "fra"],
  out: "lang/new/",
  url: "https://fanyi.baidu.com/mtpe-individual/multimodal",
};

const trans = async () => {
  try {
    for (let lan of CONFIG.list) {
      //打开浏览器，进入谷歌翻译网页
      const browser = await puppeteer.launch({
        headless: true,
        // devtools: true,
        //   slowMo: 300,
      });

      const page = await browser.newPage();
      await page.goto(
        CONFIG.url + `?query=''&lang=en2${lan}&ext_channel=Aldtype`
      );
      const total = Object.keys(en).length;
      const translateDic = {};
      let count = 0;
      for (let i in en) {
        await page.focus(".kXQpwTof");
        await page.keyboard.sendCharacter(en[i]);
        await page.waitForSelector(".sentId");
        translateDic[i] = await page.evaluate(
          () => document?.querySelector(".sentId")?.textContent
        );
        await page.waitForSelector(".text-close");
        await page.click(".text-close");
        count++;
        console.log(`${lan}:finish ${count}/${total}`);
      }
      let mode = "";
      if (!fs.existsSync(`./lang/new/${lan}.json`)) {
        mode = "wx";
      }

      await fs.writeFileSync(
        `./lang/new/${lan}.json`,
        JSON.stringify(translateDic),
        {
          flag: mode,
        }
      );
      console.log(`${lan} finish!!!`);
    }
  } catch (e) {
    console.log(e);
  }
};

trans();
